package io.github.nnkwrik.goodsservice.controller;

import io.github.nnkwrik.common.dto.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.codec.multipart.FilePart;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;


import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.MediaType;
import org.springframework.http.codec.multipart.FilePart;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import reactor.core.publisher.Mono;

import java.io.IOException;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.HashMap;
import java.util.Map;

/**
 * @title : ImgController
 * @Author : Administrator
 * @Date : 2025/4/25
 * @Version : 1.0.0
 * @Description :
 */
@RestController
@RequestMapping("/img")
public class ImgController {

    private final Logger logger = LoggerFactory.getLogger(ImgController.class);
    @Value("${file.upload-dir}")
    private String UPLOAD_DIR ; // 指定上传目录
    private final String WEB_PATH = "/static/img/";

    @PostMapping(value = "/upload")
    public Response requestBodyFlux(@RequestPart("file") MultipartFile file) throws IOException {
        logger.info("上传文件请求开始");
        try {
            if (file==null) {
                return Response.fail(HttpStatus.BAD_REQUEST.value(),"Cannot upload empty file.");
            }
            logger.info("上传文件请求，文件不为空");
            byte[] bytes = file.getBytes();
            Path path = Paths.get(UPLOAD_DIR + file.getOriginalFilename());
            Files.write(path, bytes);
            Map json = new HashMap();
            json.put("url",WEB_PATH+file.getOriginalFilename());
            logger.info("上传文件成功: " + file.getOriginalFilename());
            return Response.ok(json);
        } catch (Exception e) {
            return Response.fail(HttpStatus.INTERNAL_SERVER_ERROR.value(),"Could not upload the file: " + file.getOriginalFilename());
        }
    }


}
